<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
	<base href="/">
	<meta charset="utf-8">
	<link rel="stylesheet" href="detail/detail.css">
	<link rel="stylesheet" href="fonts/iconfont.css">
	<link rel="stylesheet" href="layui/css/layui.css">
	<style>
		/* 添加样式确保按钮文字可见 */
		.order,
		.addcart,
		.collect {
			color: white;
			font-size: 16px;
		}
	</style>
	<title>商品信息</title>
</head>

<body id="top">
<div class="top-bar tonglan">
	<div class="top-nav-wrapper w">
		<div class="top-nav-left">
		</div>
		<div class="top-nav-right">

			<ul>
				<li><a href="page/index">首页</a></li><span></span>
				<li><a href="page/orderConfirm">我的订单</a></li> <span></span>
				<li><a href="page/cart">购物车</a></li> <span></span>
				<li class="lists-title"><a href="page/profile">个人中心</a></li><span></span>
				<li>
					<a href="#" id="logoutLink">退出登录</a>
				</li>
			</ul>
		</div>
	</div>
</div>
<div class="tonglan nav-bar">
	<div class="w">
		<div class="nav-logo">
			<img src="images/LOGO_2.png" alt="">
		</div>

		<div class="menu-wrapper">
			<div class="menu-wrapper-left">
				<ul _id="categorylist">
					<li style="border-bottom: none;">
						<a href="page/index">首页
						</a>
					</li>
				</ul>
			</div>
			<div class="menu-wrapper-right">

			</div>
		</div>
	</div>
</div>
<div class="tonglan list-title-wrapper">
	<div class="w list-title">
            <span>
                <a href="page/index">TCL官网</a>
            </span>
		<span>></span>
		<span id="category1"></span>
		<span>></span>
		<span id="category2"></span>
		<span>></span>
		<span id="productName"></span>
	</div>
</div>
<div class="tonglan" style="background-color: #fff;">
	<div class="w menu-sub-wrapper">
		<div class="menu-sub-left">
			<div class="img-main">
				<img src="" alt="">
			</div>
		</div>
		<div class="menu-sub-right">
			<div class="menu-sub-top">
				<h5></h5>
			</div>
			<div class="menu-sub">
				<p>商品价: <span style="font-size: 20px;"></span><span></span></p>
				<p>原价:</p><p id="oldPrice"></p><p>元</p>
				<p>库存数量: <span id="stockQuantity"></span></p>

				<div>

					<div>
						<div>
							<img src="" alt="">
						</div>
					</div>
				</div>
			</div>
			<div class="menu-sub-bottom">
				<button style="color: white;background-color: red;" class="order">立即购买</button>
				<button class="addcart" type="button">加入购物车</button>
			</div>
			<div class="menu-sub-bottom">
				<button class="collect" type="button">收藏</button>
			</div>
		</div>
	</div>
</div>

<!--评论区域 -->
<div class="tonglan" style="background-color: #f5f5f5; padding: 20px 0;">
	<div class="w comment-wrapper">
		<h3>商品评论</h3>
		<!-- 评论筛选 -->
		<div class="comment-filter">
			<button class="filter-btn active" data-type="all">全部评论</button>
			<button class="filter-btn" data-type="good">好评</button>
			<button class="filter-btn" data-type="medium">中评</button>
			<button class="filter-btn" data-type="bad">差评</button>
		</div>
		<!-- 显示好评率和差评率 -->
		<div class="rating-statistics">
			<span id="good-rating-rate">好评率: 0%</span>
			<span id="bad-rating-rate">差评率: 0%</span>
		</div>
		<!-- 评论列表 -->
		<div id="comment-list"></div>
		<!-- 分页导航 -->
		<div id="pagination"></div>
		<!-- 发表评论 -->
		<div class="comment-form">
			<h4>发表评论</h4>
			<textarea id="comment-textarea" placeholder="请输入评论内容"></textarea>
			<select id="rating-select">
				<option value="5">好评</option>
				<option value="3">中评</option>
				<option value="1">差评</option>
			</select>
			<button id="submit-comment-btn">提交评论</button>
		</div>
	</div>
</div>

<div class="foot">
	<iframe src="footer/footer.html" frameborder="0"></iframe>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="PC/regions.js"></script>
<script src="PC/regions_picker.js"></script>
<script src="layui/layui.all.js"></script>
<script type="text/html" _id="categoryitem">
	<li>
		<a href="page/list"></a>
		<div>
			<ul class="menu-main w">

			</ul>
		</div>
	</li>
</script>
<script type="text/html" id="categorychild">
	<li>
		<a href="">
			<img src="" alt="">
			<span></span>
		</a>
	</li>
</script>
<script>
	const $ = layui.$;
	const laypage = layui.laypage;
	let currentFilterType = 'all';
	let allComments = []; // 存储全部评论数据
	let goodCount = 0;
	let mediumCount = 0;
	let badCount = 0;
	let totalCount = 0;

	// 获取 URL 中的 productid
	function getProductId() {
		const params = new URLSearchParams(window.location.search);
		const productid = params.get('productid');
		console.log('获取的 productid:', productid);
		return params.get('productid');
	}

	// 加载商品详情数据
	function loadProductDetail(productid) {
		$.ajax({
			url: 'product/list',
			type: 'GET',
			data: { productid: productid },
			dataType: 'json',
			success: function (res) {
				console.log('服务器返回的数据:', res);
				if (res.code === 0 && res.data) {
					// 从商品列表中找到对应的商品对象
					const product = res.data.find(item => item.productid === parseInt(productid));
					if (product) {
						updateProductDetail(product);
					} else {
						layer.msg("商品不存在", { icon: 2 });
						setTimeout(() => window.location.href = "index.html", 1500);
					}
				} else {
					layer.msg("商品不存在", { icon: 2 });
					setTimeout(() => window.location.href = "index.html", 1500);
				}
			},
			error: function (err) {
				console.error("加载商品失败:", err);
				layer.msg("加载商品信息失败，请稍后重试", { icon: 2 });
			}
		});
	}

	// 更新页面内容
	function updateProductDetail(product) {
		// 更新商品名称
		document.querySelector(".menu-sub-top h5").textContent = product.productname;
		document.title = product.productname + " - 商品详情";  // 更新页面标题

		// 更新价格
		const priceSpan = document.querySelector(".menu-sub span");
		priceSpan.innerHTML = `${product.price.toFixed(2)}元`;  // 保留两位小数

		// 更新主图
		const mainImg = document.querySelector(".img-main img");
		mainImg.src = product.imgurl;
		mainImg.alt = product.productname;


		// 更新面包屑导航
		const category1Span = document.getElementById('category1');
		const category2Span = document.getElementById('category2');
		const productNameSpan = document.getElementById('productName');

		category1Span.textContent = product.productcategory;
		category2Span.textContent = product.productcategory2 || '';
		productNameSpan.textContent = product.productname;

		// 更新价格为 oldprice
		const oldPriceSpan = document.getElementById('oldPrice');
		oldPriceSpan.innerHTML = `${product.oldprice.toFixed(2)}`;

		// 根据商品状态设置按钮状态
		const orderBtn = document.querySelector(".order");
		const addCartBtn = document.querySelector(".addcart");
		if (product.state === '有货') {
			orderBtn.disabled = false;
			addCartBtn.disabled = false;
			orderBtn.style.backgroundColor = 'red';
			addCartBtn.style.backgroundColor = ''; // 恢复默认背景色
		} else {
			orderBtn.disabled = true;
			addCartBtn.disabled = true;
			orderBtn.style.backgroundColor = '#ccc';
			addCartBtn.style.backgroundColor = '#ccc';
		}
		// 更新库存数量显示
		const stockQuantitySpan = document.getElementById('stockQuantity');
		stockQuantitySpan.textContent = product.stock;


	}


	// 加入购物车事件
	function bindAddCartEvent() {
		$(".addcart").click(function () {
			const productid = getProductId();
			if (!productid) {
				layer.msg("商品不存在", { icon: 2 });
				return;
			}

			$.ajax({
				url: "cart/add",
				type: "POST",
				data: { productid: productid },
				success: function (res) {

					if (res.code == 401) {
						layer.msg(res.msg, { icon: 2 });
						setTimeout(function () {
							location.href = "page/login";
						}, 2000)
					} else {
						layer.msg("已成功加入购物车", { icon: 1, time: 1800 });
					}
				},
				error: function (err) {
					layer.msg("客官请先登录", { icon: 2 });
				}
			});
		});
	}

	// 立即购买事件
	function bindBuyNowEvent() {
		$(".order").click(function () {
			const productid = getProductId();
			if (!productid) {
				layer.msg("无效的商品", { icon: 2 });
				return;
			}

			// 构建商品信息参数
			const selectedProductIds = [productid];
			const selectedCounts = [1]; // 立即购买默认数量为 1
			const productIdParam = selectedProductIds.join(',');
			const countParam = selectedCounts.join(',');
			const orderUrl = `page/order?productids=${productIdParam}&counts=${countParam}`;
			window.location.href = orderUrl;
		});
	}
	// 收藏商品事件
	function bindCollectEvent() {
		$(".collect").click(function () {
			const productid = getProductId();
			if (!productid) {
				layer.msg("商品不存在", { icon: 2 });
				return;
			}

			$.ajax({
				url: "collect/add",
				type: "POST",
				data: { productid: productid },
				success: function (res) {
					if (res.code == 401) {
						layer.msg(res.msg, { icon: 2 });
						setTimeout(function () {
							location.href = "page/login";
						}, 2000);
					} else if (res.code === 0) {
						layer.msg("已成功收藏该商品", { icon: 1, time: 1800 });
					} else if (res.code === 1) {
						layer.msg(res.msg, { icon: 2 });
					} else {
						layer.msg(res.msg, { icon: 2 });
					}
				},
				error: function (err) {
					layer.msg("收藏商品失败，请稍后重试", { icon: 2 });
				}
			});
		});
	}


	// 页面初始化
	$(document).ready(function () {
		const productid = getProductId();
		if (productid) {
			loadProductDetail(productid);
			bindAddCartEvent();  // 绑定加入购物车事件
			bindBuyNowEvent();   // 绑定立即购买事件
			bindCollectEvent();  // 绑定收藏商品事件
			$('#submit-comment-btn').on('click', function () {
				submitComment(productid);
			});
			// 绑定筛选按钮的点击事件
			$('.filter-btn').on('click', function () {
				const type = $(this).data('type');
				currentFilterType = type;
				loadComments(productid, 1);
				// 更新按钮的 active 类
				$('.filter-btn').removeClass('active');
				$(this).addClass('active');
			});

			// 加载全部评论数据
			$.ajax({
				url: 'comment/listByProductId',
				data: { productid: productid, page: 1, limit: 99999, type: '' }, // 假设全部评论不会超过 99999 条
				success: function (result) {
					if (result.code === 200) {
						allComments = result.data;
						totalCount = allComments.length;

						// 统计好评、中评、差评数量
						allComments.forEach(comment => {
							const ratingText = getRatingText(comment.type);
							if (ratingText === '好评') {
								goodCount++;
							} else if (ratingText === '中评') {
								mediumCount++;
							} else if (ratingText === '差评') {
								badCount++;
							}
						});

						// 计算好评率和差评率
						const goodRate = totalCount > 0 ? (goodCount / totalCount * 100).toFixed(2) + '%' : '0%';
						const badRate = totalCount > 0 ? (badCount / totalCount * 100).toFixed(2) + '%' : '0%';

						// 更新页面上的好评率和差评率显示
						$('#good-rating-rate').text(`好评率: ${goodRate}`);
						$('#bad-rating-rate').text(`差评率: ${badRate}`);

						// 加载第一页评论
						loadComments(productid, 1);
					} else {
						layer.msg('获取全部评论列表失败: ' + result.msg, { icon: 2 });
					}
				},
				error: function (error) {
					console.error('获取全部评论列表失败:', error);
					layer.msg('获取全部评论列表失败，请稍后重试', { icon: 2 });
				}
			});
		} else {
			layer.msg("商品参数错误", { icon: 2 });
			setTimeout(() => window.location.href = "index.html", 1000);
		}
	});

	//回到顶部按钮事件
	const backToTopBtn = document.getElementById('backToTopBtn');
	if (backToTopBtn) {
		backToTopBtn.addEventListener('click', function () {
			window.scrollTo({
				top: 0,
				behavior: 'smooth'
			});
		});
	}

	$.ajax({
		url: 'category/list',
		data: { id: -1 },
		success: function (result) {
			let data = result.data;
			console.log(data);

			// 筛选出 pid 为 -1 的父级分类
			const parentCategories = data.filter(item => item.pid === -1);

			parentCategories.forEach((parent) => {
				let item = $('script[_id="categoryitem"]').text();
				let $item = $(item);
				$item.children("a").text(parent.categoryname);
				$item.children("a").attr("href", `page/list?category=${parent.categoryname}`);
				let $ul = $item.find("ul");

				// 发起请求获取子分类
				$.ajax({
					url: "category/getChildren",
					data: { id: parent.categoryid },
					success: function (res) {
						// 内层循环使用不同的变量名 j
						for (let j = 0; j < res.length; j++) {
							let childtext = $("#categorychild").text();
							let $child = $(childtext);
							$child.find("span").text(res[j].categoryname);
							$child.find("img").attr("src", res[j].imgurl);
							$child.find("a").attr("href", `page/list?category=${res[j].categoryname}`);
							$ul.append($child);
						}
					},
					error: function (error) {
						console.error(`获取 ${parent.categoryname} 的子分类失败:`, error);
					}
				});

				$('ul[_id="categorylist"]').append($item);
			});
		},
		error: function (error) {
			console.error('获取分类列表失败:', error);
		}
	});

	// 退出登录逻辑
	const logoutLink = document.getElementById('logoutLink');
	logoutLink.addEventListener('click', function (e) {
		e.preventDefault(); // 阻止默认的链接跳转行为
		// 弹出确认提示框
		if (confirm('确定要退出登录吗？')) {
			$.ajax({
				url: 'logout', // 后端退出登录的接口地址
				method: 'GET',
				success: function (response) {
					if (response.code === 200) {
						// 退出登录成功，给出提示并跳转到登录页面
						alert(response.msg);
						window.location.href = 'page/login';
					} else {
						// 退出登录失败，给出提示
						alert(response.msg);
					}
				},
				error: function (error) {
					console.error('退出登录失败:', error);
					alert('退出登录时发生错误，请稍后再试。');
				}
			});
		}
	});

	// 格式化时间函数
	function formatTime(isoTime) {
		const date = new Date(isoTime);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		const seconds = String(date.getSeconds()).padStart(2, '0');
		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}

	// 加载评论
	function loadComments(productid, page) {
		let typeParam = '';
		if (currentFilterType === 'good') {
			typeParam = 1;
		} else if (currentFilterType ==='medium') {
			typeParam = 2;
		} else if (currentFilterType === 'bad') {
			typeParam = 3;
		}
		$.ajax({
			url: 'comment/listByProductId',
			data: { productid: productid, page: page, limit: 10, type: typeParam },
			success: function (result) {
				if (result.code === 200) {
					const comments = result.data;
					const container = $('#comment-list');
					container.empty();

					comments.forEach(comment => {
						const ratingText = getRatingText(comment.type); // 根据 type 获取评价文本
						const formattedTime = formatTime(comment.addtime); // 格式化时间
						const html = `
                                <div class="comment-item">
                                    <div class="comment-user">
                                        <img src="${comment.imgurl}" alt="${comment.username}" class="comment-user-avatar">
                                        <span class="comment-user-name">${comment.username}</span>
                                    </div>
                                    <p class="comment-rating">${ratingText}</p>
                                    <p class="comment-content">${comment.text}</p>
                                    <p class="comment-time">${formattedTime}</p>
                                </div>
                            `;
						container.append(html);
					});

					// 生成分页导航
					laypage.render({
						elem: 'pagination',
						count: result.total, // 总数据量
						limit: 10, // 每页显示数量
						curr: page, // 当前页码
						layout: ['prev', 'page', 'next', 'count'],
						jump: function (obj, first) {
							if (!first) {
								loadComments(productid, obj.curr);
							}
						}
					});

				} else {
					layer.msg('获取评论列表失败: ' + result.msg, { icon: 2 });
				}
			},
			error: function (error) {
				console.error('获取评论列表失败:', error);
				layer.msg('获取评论列表失败，请稍后重试', { icon: 2 });
			}
		});
	}

	// 提交评论
	function submitComment(productid) {
		const commentText = $('#comment-textarea').val();
		const rating = $('#rating-select').val();
		if (!commentText) {
			layer.msg('请输入评论内容', { icon: 2 });
			return;
		}

		// 映射 rating 到数据库的 type 字段
		let commentType;
		if (rating === '5') {
			commentType = 1; // 好评
		} else if (rating === '3') {
			commentType = 2; // 中评
		} else if (rating === '1') {
			commentType = 3; // 差评
		}

		$.ajax({
			url: 'comment/add',
			method: 'POST',
			contentType: 'application/json',
			data: JSON.stringify({
				productid: productid,
				text: commentText,
				type: commentType, // 使用映射后的 type 字段
			}),
			success: function (result) {
				if (result.code === 200) {
					layer.msg('评论提交成功', { icon: 1 });
					$('#comment-textarea').val('');
					// 重新加载全部评论数据
					$.ajax({
						url: 'comment/listByProductId',
						data: { productid: productid, page: 1, limit: 99999, type: '' },
						success: function (res) {
							if (res.code === 200) {
								allComments = res.data;
								totalCount = allComments.length;
								goodCount = 0;
								mediumCount = 0;
								badCount = 0;

								// 重新统计好评、中评、差评数量
								allComments.forEach(comment => {
									const ratingText = getRatingText(comment.type);
									if (ratingText === '好评') {
										goodCount++;
									} else if (ratingText === '中评') {
										mediumCount++;
									} else if (ratingText === '差评') {
										badCount++;
									}
								});

								// 重新计算好评率和差评率
								const goodRate = totalCount > 0 ? (goodCount / totalCount * 100).toFixed(2) + '%' : '0%';
								const badRate = totalCount > 0 ? (badCount / totalCount * 100).toFixed(2) + '%' : '0%';

								// 更新页面上的好评率和差评率显示
								$('#good-rating-rate').text(`好评率: ${goodRate}`);
								$('#bad-rating-rate').text(`差评率: ${badRate}`);

								// 加载第一页评论
								loadComments(productid, 1);
							} else {
								layer.msg('获取全部评论列表失败: ' + res.msg, { icon: 2 });
							}
						},
						error: function (err) {
							console.error('获取全部评论列表失败:', err);
							layer.msg('获取全部评论列表失败，请稍后重试', { icon: 2 });
						}
					});
				} else {
					layer.msg('评论提交失败: ' + result.msg, { icon: 2 });
				}
			},
			error: function (error) {
				console.error('评论提交失败:', error);
				layer.msg('评论提交失败，请稍后重试', { icon: 2 });
			}
		});
	}

	// 筛选评论
	function filterComments(type) {
		const comments = $('.comment-item');
		comments.hide();
		if (type === 'all') {
			comments.show();
		} else if (type === 'good') {
			comments.filter(function () {
				return $(this).find('.comment-rating').text() === '好评';
			}).show();
		} else if (type === 'medium') {
			comments.filter(function () {
				return $(this).find('.comment-rating').text() === '中评';
			}).show();
		} else if (type === 'bad') {
			comments.filter(function () {
				return $(this).find('.comment-rating').text() === '差评';
			}).show();
		}
	}

	// 根据评分获取评价文本
	// 根据 type 获取评价文本
	function getRatingText(type) {
		switch (type) {
			case 1:
				return '好评';
			case 2:
				return '中评';
			case 3:
				return '差评';
			default:
				return '未知评价';
		}
	}

</script>
</body>

</html>